<template>
  <div class="player-box"><d-player ref="video" :options="playerOptions" /></div>
</template>

<script>
import DPlayer from 'vue-dplayer';
import 'vue-dplayer/dist/vue-dplayer.css';
import Hls from 'hls.js';

export default {
  components: {
    DPlayer
  },
  props: {
    file: {
      type: Object,
      required: true
    },
    preview: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const playUrl = this.file.playurl;
    console.log(playUrl);
    // const ext = playUrl.split()
    const questionMarkIndex = playUrl ? playUrl.indexOf('?') : -1; // 查找问号的位置
    let type;
    if (questionMarkIndex !== -1) {
      type = playUrl.substring(questionMarkIndex - 4, questionMarkIndex); // 根据问号的位置截取子字符串
    } else {
      type = playUrl.slice(playUrl.length - 4, playUrl.length);
    }

    return {
      playerOptions: {
        container: this.$refs.player, // 播放器容器
        autoplay: true,
        lang: 'zh-cn',
        video: {
          url: playUrl,
          // type: 'customHls',
          type: type === 'm3u8' ? 'customHls' : 'auto',
          customType: {
            customHls: function(video, player) {
              const hls = new Hls();
              hls.loadSource(video.src);
              hls.attachMedia(video);
            }
          }
        },
        contextmenu: []
      }
    };
  },
  watch: {
    preview(val) {
      if (val === false) {
        this.$refs.video.dp.pause();
      } else {
        this.$refs.video.dp.play();
      }
    }
  }
};
</script>

<style scoped>
.player-box {
  display: inline-block;
  width: 100%;
  height: auto;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.player-box >>> .dplayer-video-current {
  max-height: 60vh;
}

.player-box:hover {
  display: block;
}
</style>
